import {
	setStorageSync,
	getStorageSync
} from '@/utils/storage.js'
import {
	getChapterDetail
} from "@/api/chapter";
import _ from 'lodash'
const readModules = {
	state: {
		currentReadBookInfo: {},
		historyReadList: getStorageSync('historyReadList') || [],
		lastReadBookInfo: getStorageSync('lastReadBookInfo') || {
			bookId: 0,
			chapterId: 0
		}
	},
	mutations: {
		SET_CURRENT_READ_BOOK_INFO(state, currentReadBookInfo) {
			state.currentReadBookInfo = currentReadBookInfo
		},
		SET_LAST_READ_BOOK_INFO(state, {
			bookId,
			chapterId
		}) {
			state.lastReadBookInfo = {
				bookId,
				chapterId
			}
			setStorageSync('lastReadBookInfo', {
				bookId,
				chapterId
			})
		},
		SET_HISTORY_READ_LIST(state, historyReadList) {
			state.historyReadList = historyReadList
			setStorageSync('historyReadList', historyReadList)
		}
	},
	actions: {
		getReadBookInfo({
			commit,
			state
		}, bookId) {
			return new Promise((resolve, reject) => {
				getChapterDetail({
					bookId
				}).then(res => {
					commit('SET_CURRENT_READ_BOOK_INFO',
						res.data)
					resolve('ok')
				}).catch(e => {
					reject(e)
				})
			})
		},
		updateHistoryReadList({
			commit,
			state
		}, bookInfo) {
			return new Promise((resolve, reject) => {
				try {
					const historyReadList = _.cloneDeep(state.historyReadList)
					const {
						bookId
					} = bookInfo
					let currentIndex = historyReadList.findIndex(item => item.bookId == bookId)
					const lastReadTime = new Date().getTime()
					if (currentIndex !== -1) { // 更新时间
						historyReadList[currentIndex].lastReadTime = lastReadTime
					} else {
						const {
							chapter_count,
							click_num,
							image,
							first_chapter_id,
							is_book_shelf,
							is_over,
							last_chapter_id,
							name,
							new_chapter,
							writer,
							updated_at,
							type
						} = state.currentReadBookInfo
						Object.assign(bookInfo,{
							chapter_count,
							click_num,
							image,
							first_chapter_id,
							is_book_shelf,
							is_over,
							last_chapter_id,
							name,
							new_chapter,
							writer,
							updated_at,
							type,
							lastReadTime
						})
						historyReadList.push(bookInfo)
					}
					commit('SET_HISTORY_READ_LIST', historyReadList)
					resolve('ok')
				} catch (e) {
					reject(e)
				}
			})
		}
	}
}

export default readModules
